package cz.via.wowss.dao;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javassist.NotFoundException;

import javax.persistence.EntityManager;

import cz.via.wowss.controller.MainController;
import cz.via.wowss.entities.Player;

public class GameDao implements IGameDao {

	public int logon(String user, String password) {
		Player entity = MainController.emf
				.createEntityManager()
				.createQuery("SELECT p FROM Player p WHERE p.name='" + user + "'",
						Player.class).getSingleResult();

		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA-256");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		try {
			md.update(password.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] digest = md.digest();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < digest.length; i++) {
			sb.append(Integer.toString((digest[i] & 0xff) + 0x100, 16)
					.substring(1));
		}

		if (entity.getPassword().equals(sb.toString())) {
			return entity.getId();
		} else {
			return -1;
		}
	}

	public int getPlayerId(String player) {
		return MainController.emf
				.createEntityManager()
				.createQuery("SELECT p FROM Player p WHERE p.name='" + player + "'",
						Player.class).getSingleResult().getId();
	}

	public Player getPlayerById(int id) {
		EntityManager em = MainController.emf.createEntityManager();
		Player entity = null;
		try {
			entity = em.find(Player.class, id);
			if (entity == null)
				try {
					throw new NotFoundException(
							"Could not find any player with ID " + id);
				} catch (NotFoundException e) {
					e.printStackTrace();
				}
		} finally {
			em.close();
		}
		return entity;
	}

	public double getPlayerMoney(String name) {
		return MainController.emf
				.createEntityManager()
				.createQuery("SELECT p FROM Player p WHERE p.name='" + name + "'",
						Player.class).getSingleResult().getMoney()
				.doubleValue();
	}

}
